package com.chat;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class MsgSender implements Runnable {
    public void run(){
        // 指定发送端的IP & 端口。(也可以不指定)
        DatagramSocket datagramSocket = null;
        Scanner scanner = new Scanner(System.in);
        InetAddress myIp = null;
        InetAddress reIp = null;
        try {
            myIp = InetAddress.getByName("192.168.254.101");
            reIp = InetAddress.getByName("192.168.254.101");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        while(true){
            try {
                datagramSocket = new DatagramSocket(7000,myIp);
                System.out.print("我说：");
                String msg = scanner.nextLine();
                DatagramPacket msgBag = new DatagramPacket(msg.getBytes(),msg.getBytes().length,reIp,7001);
                datagramSocket.send(msgBag);
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(datagramSocket != null){
                    datagramSocket.close();
                }
            }
        }
    }
}
